from datetime import datetime
from typing import Tuple, Union, Any

from sqlalchemy import and_

from app.models.data_base_models import LogSearchPriceExe, User
from app.services import get_base_session


class LogSearchPriceExeServices:

    @staticmethod
    def addLogSearchPriceExe(user: User, search_result: Union[dict, None], search_time: datetime, param_dp, param_cpn) -> Tuple[bool, str]:
        if user is None or search_time is None:
            return False, "参数问题"
        if not isinstance(search_result, dict):
            logSearchPriceExe = LogSearchPriceExe(
                search_time=search_time,
                search_user_id=user.id,
                search_user_name=user.user_name,
                param_delivery_price=param_dp,
                param_code_package_num=param_cpn,
                result_delivery_price=None,
                result_total_package_num=None,
                result_total_promotion_base_price=None,
                result_total_billing=None,
                result_total_day_promotion_base_price=None,
                result_total_piece_num=None,
                result_total_gift_cost=None,
                result_discount_rate=None,
                result_is_lower_promotion_price=None,
                result_is_lower_promotion_day_price=None,
                result_piece_price=None,
                result_gift_rate=None
            )
        else:
            logSearchPriceExe = LogSearchPriceExe(
                search_time=search_time,
                search_user_id=user.id,
                search_user_name=user.user_name,
                param_delivery_price=param_dp,
                param_code_package_num=param_cpn,
                result_delivery_price=search_result['到手价'],
                result_total_package_num=search_result['总包数合计'],
                result_total_promotion_base_price=search_result['总大促底价合计'],
                result_total_billing=search_result['总开单合计'],
                result_total_day_promotion_base_price=search_result['总日促底价合计'],
                result_total_piece_num=search_result['总片数合计'],
                result_total_gift_cost=search_result['总赠品成本合计'],
                result_discount_rate=search_result['折扣费率'],
                result_is_lower_promotion_price=search_result['是否破大促价'],
                result_is_lower_promotion_day_price=search_result['是否破日促价'],
                result_piece_price=search_result['片单价'],
                result_gift_rate=search_result['赠品占比']
            )
        session = get_base_session()
        try:
            session.add(logSearchPriceExe)
            session.commit()
            return True, "写入成功"
        except Exception as e:
            return False, str(e)
        finally:
            session.close()

    @staticmethod
    def getAllLogSearchPriceExe() -> Tuple[bool, Union[list[LogSearchPriceExe], str, None]]:
        session = get_base_session()
        try:
            res = session.query(LogSearchPriceExe).all()
            return True, res
        except Exception as e:
            return False, str(e)
        finally:
            session.close()

    @staticmethod
    def getLogSearchPriceExes(queryDict: dict[str, Any]) -> Tuple[bool, Union[list[LogSearchPriceExe], str, None]]:
        session = get_base_session()
        try:
            conditions = []
            res = session.query(LogSearchPriceExe)
            startTime = queryDict.get('startTime')
            if startTime is not None and isinstance(startTime, str):
                startTime = datetime.strptime(startTime, '%Y-%m-%d %H:%M:%S')
                conditions.append(LogSearchPriceExe.search_time >= startTime)
            endTime = queryDict.get('endTime')
            if endTime is not None and isinstance(endTime, str):
                endTime = datetime.strptime(endTime, '%Y-%m-%d %H:%M:%S')
                conditions.append(LogSearchPriceExe.search_time <= endTime)
            searchUserName = queryDict.get('searchUserName')
            if searchUserName is not None and isinstance(searchUserName, str):
                conditions.append(LogSearchPriceExe.search_user_name.like(searchUserName))
            if len(conditions) > 0:
                res = res.filter(and_(*conditions))
            page_index = queryDict.get("pageIndex")
            if page_index is not None and not isinstance(page_index, int):
                page_index = int(page_index) if isinstance(page_index, str) else None
            page_size = queryDict.get("pageSize")
            if page_size is not None and not isinstance(page_size, int):
                page_size = int(page_size) if isinstance(page_size, str) else None
            if page_index is not None and page_size is not None and page_index > 0:
                res = res.offset(page_size * (page_index - 1)).limit(page_size)
            return True, res.all()
        except Exception as e:
            return False, str(e)
        finally:
            session.close()
